package tgc.edu.ljc.chatRoom.web.websocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@ServerEndpoint(value = "/oneToMany/{user}")
@Component
public class ChatRoomService {
	private static CopyOnWriteArraySet<Client> clients=new CopyOnWriteArraySet<>();
	private ObjectMapper mapper=new ObjectMapper();
	private Session session;
	
	
	private void sendMsg(Msg msg) {
		for (Client client : clients) {
			try {
				client.getsParent().session.getAsyncRemote().sendText(mapper.writeValueAsString(msg));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void sendMsg(Msg msg,String user)  {
		Client client = find(user);
		if(client!=null) {
			try {
				client.getsParent().session.getBasicRemote().sendText(mapper.writeValueAsString(msg));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private Client find(String user){
		for (Client client : clients) {
			if(user.equals(client.getUser())) {
				return client;
			}
		}
		return null;
	}
	
	@OnOpen
	public void onOpen(Session session, @PathParam(value = "user")String user) {
		this.session=session;
		clients.add(new Client(user, this));
		List<String> users=new ArrayList<>();
		for(Client c:clients) {
			users.add(c.getUser());
		}
		String message=user+ "进入了聊天室,聊天室总人数："+clients.size();
		Msg msg=new Msg();
		msg.setUser("sysout");
		msg.setType("sysout");
		msg.setMsg(message);
		msg.setUsers(users);
		System.out.println(message);
		sendMsg(msg);
	}
	
	@OnClose
	public void onClose(Session session,@PathParam(value = "user")String user) {
		clients.remove(find(user));
		List<String> users=new ArrayList<>();
		for(Client c:clients) {
			users.add(c.getUser());
		}
		Msg msg=new Msg();
		msg.setUser("sysout");
		msg.setType("sysout");
		msg.setUsers(users);
		msg.setMsg(user+"退出了聊天室，聊天室总人数："+clients.size());
		System.out.println(user+"退出了聊天室，聊天室总人数："+clients.size());
		sendMsg(msg);
	}
	
	@OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }
	
	@OnMessage
	public void onMessage(String message,Session session,@PathParam(value = "user")String user) {
		ObjectMapper mapper= new ObjectMapper();
		Msg msg;
		try {
			msg = mapper.readValue(message, Msg.class);
			String user2 = msg.getUser();
			if("all".equals(user2)) {
				msg.setUser(user);
				msg.setUsers(null);
				sendMsg(msg);
				return;
			}
			msg.setUser(user);
			String[] users = user2.split(",");
			String txt=msg.getMsg();
			for (String user3 : users) {
				txt="@"+user3+" "+txt;
			}
			msg.setMsg(txt);
			sendMsg(msg, user);
			for (String user3 : users) {
				sendMsg(msg, user3);
			}
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
	}
	
	
}
